﻿#region Đào Mạnh Hòa
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace GUI.BanBuon
{
    public partial class frmXuLy : Form
    {
        #region Delegate
        public delegate void GetString(Boolean capnhat);
        public GetString GetData;
        #endregion

        #region khởi tạo biến
        #region biến
        public bool kiemtra = false;
        bool checkClose = false;
        bool checkDDH = false;
        //Entities.QuyDoiDonViTinh[] quidoidvt;
        Entities.HDBanBuon hdbanbuon;
        Entities.HDBanBuon temp;
        Entities.ChiTietHDBanBuon[] chitiethdbanbuon;
        Entities.ChiTietHDBanBuon[] hienthi;
        Entities.ChiTietHDBanBuon[] templv;
        Entities.DiemThuongKhachHang[] diemthuongkhachhang;
        Entities.TyLeTinh[] tyletinh;
        Entities.ChiTietHDBanBuon save;
        Entities.Thue[] thue;
        Entities.TienTe[] tiente;
        Entities.KhuyenMaiTangHang[] khuyenmaitanghang;
        Entities.ChiTietKhuyenMaiTangHang[] chitietkhuyenmaitanghang;
        Entities.HangHoa[] hanghoa;
        Entities.ChiTietKhoHang[] chitietkhohang;
        Entities.KhachHang khachhang;
        Entities.ChinhSachGiaHangHoa[] chinhsachgiahanghoa;
        Entities.ChiTietChinhSachGiaHangHoa[] chitietchinhsachgiahanghoa;
        Entities.GoiHang[] goihang;
        Entities.ChiTietGoiHang[] chitietgoihang;
        Entities.DonDatHangKH dondathangkh;
        Entities.ChiTietDonHangKH[] chitietdondathangkh;

        double chietkhauthuongmai;
        bool checkgoihang = false;
        bool khuyenmai = false;
        string mahanghoa = "";
        int soluong = 1;
        int chietkhau = 0;
        string thuegtgt = "0";
        string dongia = "0";
        double tongtienhang, tienchietkhau, tienchietkhauthuongmai, tongthuegtgt, tongtien, thanhtien, tongtienhangchuachietkhau, duno;
        string hanhDong;
        Entities.SelectAll selectall;
        #endregion
        public frmXuLy()
        {
            InitializeComponent();
            try
            {
                Entities.CaiDatKho kho = Entitystatic.ViewFile();
                makho = kho.MaKho;
                tenkho = kho.TenKho;
                //manhanvien = UtilitiesVariable.User.NhanVienID;
                //tennhanvien = UtilitiesVariable.User.TenNhanVien;
                date = Entitystatic.date;
                selectall = new Entities.SelectAll("BanBuon", makho);
                selectall = Common.StaticVariable.InterfaceObject.SelectAll(selectall);
                //selectall = BusinessLogic.SelectAll.BanBuon(makho);
                thue = selectall.Thue;
                hanghoa = selectall.HangHoa;
                chitietkhohang = selectall.ChiTietKhoHang;
                //quidoidvt = selectall.QuyDoiDonViTinh;
                diemthuongkhachhang = selectall.DiemThuongKhachHang;
                tyletinh = selectall.TyLeTinh;

                hanhDong = Common.Constants.Insert;

                mahdbanbuon = getID();
            }
            catch
            {
            }
        }

        public frmXuLy(Entities.HDBanBuon hdbanbuon)
        {
            InitializeComponent();
            try
            {
                this.hdbanbuon = hdbanbuon;
                Entities.CaiDatKho kho = Entitystatic.ViewFile();
                makho = kho.MaKho;
                tenkho = kho.TenKho;
                thue = Common.StaticVariable.InterfaceObject.SelectThue(new Entities.Thue("1"));
                date = Entitystatic.date;
                lblNoHienThoi.Text = hdbanbuon.NoHienThoi;
                kiemtra = true;
                btnThanhToan.Enabled = true;
                temp = hdbanbuon;
                this.hdbanbuon = hdbanbuon;
                chitiethdbanbuon = HienThiChiTiet(hdbanbuon);
                templv = chitiethdbanbuon;

                dgvHienThi.DataSource = chitiethdbanbuon;
                fix();
                XuLyDuLieu(hdbanbuon);
                hanhDong = Common.Constants.Update;
                tienchietkhauthuongmai = (double.Parse(TongTien()) * hdbanbuon.PhanTramChietKhauThuongmai) / 100;

                txtTongTien.Text = Common.Utilities.FormatMoney(hdbanbuon.TongTienThanhToan).ToString();
            }
            catch
            {
            }
        }

        void fix()
        {
            for (int i = 0; i < dgvHienThi.ColumnCount; i++)
            {
                dgvHienThi.Columns[i].Visible = false;
            }
            dgvHienThi.ReadOnly = true;
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanBuon.SoLuong].Visible = true;
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanBuon.TenHangHoa].Visible = true;
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanBuon.DonGia].Visible = true;
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanBuon.PhanTramChietKhau].Visible = true;
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanBuon.ThueGTGT].Visible = true;
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanBuon.ThanhTien].Visible = true;

            dgvHienThi.Columns[Common.Constants.ChiTietHDBanBuon.SoLuong].HeaderText = "Số Lượng";
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanBuon.TenHangHoa].HeaderText = "Tên Hàng";
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanBuon.DonGia].HeaderText = "Giá";
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanBuon.PhanTramChietKhau].HeaderText = "%CK";
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanBuon.ThueGTGT].HeaderText = "%GTGT";
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanBuon.ThanhTien].HeaderText = "Thành Tiền";

            dgvHienThi.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvHienThi.AllowUserToAddRows = false;
            dgvHienThi.AllowUserToDeleteRows = false;
            dgvHienThi.AllowUserToResizeRows = false;
            dgvHienThi.RowHeadersVisible = false;
        }

        public Entities.ChiTietHDBanBuon[] HienThi()
        {
            try
            {
                Entities.ChiTietHDBanBuon[] temp = Common.StaticVariable.InterfaceObject.SelectChiTietHDBanBuon();
                return temp;
            }
            catch
            {
                return new Entities.ChiTietHDBanBuon[0];
            }

        }

        public Entities.ChiTietHDBanBuon[] HienThiChiTiet(Entities.HDBanBuon hdbanle)
        {
            try
            {
                List<Entities.ChiTietHDBanBuon> array = new List<Entities.ChiTietHDBanBuon>();
                Entities.ChiTietHDBanBuon[] temp = Common.StaticVariable.InterfaceObject.SelectChiTietHDBanBuon();
                foreach (Entities.ChiTietHDBanBuon item in temp)
                {
                    if (item.MaHDBanBuon == hdbanle.MaHDBanBuon)
                    {
                        item.DonGia = Common.Utilities.FormatMoney(item.DonGia);
                        item.ThanhTien = Common.Utilities.FormatMoney(item.ThanhTien);
                        array.Add(item);
                    }
                }
                Entities.ChiTietHDBanBuon[] chitiethdbanbuon = (Entities.ChiTietHDBanBuon[])array.ToArray();
                return chitiethdbanbuon;
            }
            catch
            {
                return new Entities.ChiTietHDBanBuon[0];
            }

        }

        #endregion

        #region Thanh Toán
        void ThanhToan()
        {
            if (hanhDong != Common.Constants.Insert)
            {
                if (hdbanbuon == null)
                {
                    hdbanbuon = XuLyObject(Common.Constants.Insert);
                    if (hdbanbuon == null)
                    {
                        return;
                    }
                }
                TongTien();
                frmThanhToan xuly = new frmThanhToan(hdbanbuon, tongtien, hanhDong, tienchietkhauthuongmai);
                xuly.ShowDialog();
            }
            else
            {
                try
                {
                    if (!btnThanhToan.Enabled)
                    {
                        return;
                    }
                    chitiethdbanbuon = (Entities.ChiTietHDBanBuon[])dgvHienThi.DataSource;
                    // check object
                    if (chitiethdbanbuon == null || chitiethdbanbuon.Length == 0)
                    {
                        MessageBox.Show(Common.MSG.MSG23(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                        return;
                    }

                    if (dtpHanThanhToan.Text == "")
                    {
                        MessageBox.Show(Common.MSG.MSG13("Hạn thanh toán"), Common.MSG.TieuDe, MessageBoxButtons.OK);
                        dtpHanThanhToan.Focus();
                        return;
                    }

                    if (hdbanbuon == null)
                    {
                        hdbanbuon = XuLyObject(Common.Constants.Insert);
                        if (hdbanbuon == null)
                        {
                            return;
                        }
                    }
                    // dgvHienThi.DataSource = XuLyChinhSachGiaHangHoa(templv);
                    if (templv == null)
                        templv = (Entities.ChiTietHDBanBuon[])dgvHienThi.DataSource;
                    txtTongTien.Text = Common.Utilities.FormatMoney(Convert.ToString(double.Parse(TongTien()) - tienchietkhauthuongmai));
                    hdbanbuon.ChietKhau = (tienchietkhauthuongmai).ToString();
                    hdbanbuon.TongTienThanhToan = txtTongTien.Text;
                    hdbanbuon.ThueGTGT = TinhThue();

                    frmThanhToan xuly = new frmThanhToan(hdbanbuon, tienchietkhauthuongmai);
                    xuly.ShowDialog();
                    if (!frmThanhToan.kiemtra)
                    {
                        hdbanbuon = frmThanhToan.hdbanbuon;

                        duno = frmThanhToan.duno;
                        frmThanhToan.hdbanbuon = null;
                        frmThanhToan.duno = 0;
                        // check conflic insert
                        if (!CheckConflicInsert(hdbanbuon))
                        {
                            MessageBox.Show(Common.MSG.MSG5(hdbanbuon.MaHDBanBuon), Common.MSG.TieuDe, MessageBoxButtons.OK);
                            GetData(true);
                            mahdbanbuon = mahdbanbuonmoi;
                            hdbanbuon.MaHDBanBuon = mahdbanbuon;
                            return;
                        }
                        // đặt số lượng đã trả = số lượng
                        for (int i = 0; i < chitiethdbanbuon.Length; i++)
                        {
                            chitiethdbanbuon[i].MaHDBanBuon = mahdbanbuon;
                            chitiethdbanbuon[i].SoLuongConlai = chitiethdbanbuon[i].SoLuong;
                        }
                        Entities.KhachHang kh = null;
                        // update dư nợ khách hàng
                        if (duno > 0)
                        {
                            khachhang.DuNo = duno.ToString();
                            khachhang.HanhDong = Common.Constants.Update;
                            kh = khachhang;
                        }
                        hdbanbuon.KhachHang = kh;
                        hdbanbuon.TaiKhoan = UtilitiesVariable.User;
                        hdbanbuon.ChiTietKhoHang = CheckListView(chitiethdbanbuon);
                        hdbanbuon.PhieuTTKH = CheckPhieuTTKH(hdbanbuon);
                        hdbanbuon.ChiTietPhieuTTKH = CheckChiTietPhieuTTKH(hdbanbuon, hdbanbuon.PhieuTTKH);
                        hdbanbuon.ChiTietHDBanBuon = chitiethdbanbuon;
                        // check update giá trị còn lại thẻ vip
                        if (hdbanbuon.MaTheVip.Length != 0)
                        {
                            Entities.TheVip thevip = XuLyObjectTheVip(Common.Constants.Update);
                            hdbanbuon.TheVip = thevip;
                        }
                        // check update điểm thưởng khách hàng
                        if (txtMaKhachHang.Text.Length != 0 && txtMaKhachHang.Text != "<F4 - Tra cứu>")
                        {
                            Entities.DiemThuongKhachHang diemthuongkhachhang = XuLyDiemThuongKhachHang();
                            // check update
                            if (diemthuongkhachhang != null)
                                hdbanbuon.DiemThuongKhachHang = diemthuongkhachhang;
                        }
                        if (checkDDH)
                        {
                            Entities.DonDatHangKH ddh = new Entities.DonDatHangKH();
                            ddh.MaDonDatHangKH = txtDonDatHang.Text;
                            hdbanbuon.DonDatHangKH = ddh;
                        }
                        // check insert
                        if (Common.StaticVariable.InterfaceObject.InsertUpdateHDBanBuon(hdbanbuon) == 0)
                        {
                            MessageBox.Show(Common.MSG.MSG15(hdbanbuon.MaHDBanBuon), Common.MSG.TieuDe, MessageBoxButtons.OK);
                            return;
                        }

                        this.Enabled = false;
                        In(hdbanbuon);
                        this.Enabled = true;
                        checkClose = true;
                        hdbanbuon = null;
                        this.Close();
                    }
                    frmThanhToan.kiemtra = false;

                }
                catch
                {
                    MessageBox.Show(Common.MSG.MSG15(hdbanbuon.MaHDBanBuon), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }
                finally
                {
                    txtMaHangHoa.Focus();
                }
            }
        }

        Entities.PhieuTTCuaKH CheckPhieuTTKH(Entities.HDBanBuon hdbanbuon)
        {
            Entities.PhieuTTCuaKH pt = new Entities.PhieuTTCuaKH();
            pt.HanhDong = Common.Constants.Insert;
            pt.MaPhieuTTCuaKH = new PhieuTTCuaKH.frmXuLy("").getID();
            pt.NgayLap = DateTime.Parse(date.ToString("MM/dd/yyyy"));
            pt.MaKhachHang = hdbanbuon.MaKhachHang;
            pt.TenKhachHang = hdbanbuon.TenKhachHang;
            pt.TongThanhToan = hdbanbuon.ThanhToanNgay;
            pt.LoaiPhieu = false;
            pt.NoHienThoi = hdbanbuon.NoHienThoi;
            pt.MaKho = makho;
            pt.NguoiNop = "";
            pt.MaNhanVien = "";
            pt.GhiChu = "";
            pt.Deleted = false;
            return pt;
        }

        Entities.ChiTietPhieuTTCuaKH CheckChiTietPhieuTTKH(Entities.HDBanBuon hdbanbuon, Entities.PhieuTTCuaKH phieuttkh)
        {
            Entities.ChiTietPhieuTTCuaKH ctpttkh = new Entities.ChiTietPhieuTTCuaKH();
            ctpttkh.Deleted = false;
            ctpttkh.GhiChu = "";
            ctpttkh.HanhDong = Common.Constants.Insert;
            ctpttkh.MaHDBanHang = mahdbanbuon;
            ctpttkh.MaPhieuTTCuaKH = phieuttkh.MaPhieuTTCuaKH;
            ctpttkh.TongTienThanhToan = hdbanbuon.TongTienThanhToan;
            ctpttkh.SoNo = (double.Parse(hdbanbuon.TongTienThanhToan) - double.Parse(hdbanbuon.ThanhToanNgay) - double.Parse(hdbanbuon.ThanhToanSauKhiLapPhieu)).ToString();
            ctpttkh.ThanhToan = hdbanbuon.ThanhToanNgay;
            ctpttkh.TongTienThanhToan = hdbanbuon.TongTienThanhToan;
            return ctpttkh;
        }
        Entities.ChiTietKhoHang[] CheckListView(Entities.ChiTietHDBanBuon[] hienthi)
        {
            try
            {
                ArrayList array = new ArrayList();
                foreach (Entities.ChiTietHDBanBuon item in hienthi)
                {
                    bool kt = false;
                    int sotang = 0;
                    Entities.ChiTietKhoHang ctkh = new Entities.ChiTietKhoHang();
                    // lấy số lượng trong kho
                    foreach (Entities.ChiTietKhoHang item1 in chitietkhohang)
                    {
                        if (item1.MaHangHoa.ToUpper() == item.MaHangHoa.ToUpper())
                        {
                            kt = true;
                            break;
                        }
                        sotang++;
                    }
                    if (!kt)
                    {
                        foreach (Entities.GoiHang item1 in goihang)
                        {
                            if (item.MaHangHoa == item1.MaGoiHang.ToUpper())
                            {
                                foreach (Entities.ChiTietGoiHang item2 in chitietgoihang)
                                {
                                    if (item1.MaGoiHang.ToUpper() == item2.MaGoiHang.ToUpper())
                                    {
                                        ctkh = new Entities.ChiTietKhoHang();
                                        ctkh.MaKho = makho;
                                        ctkh.MaHangHoa = item2.MaHangHoa.ToUpper();
                                        ctkh.SoLuong = (item2.SoLuong * item.SoLuong).ToString();
                                        array.Add(ctkh);
                                    }
                                }
                                break;
                            }
                        }
                    }
                    else
                    {
                        ctkh = new Entities.ChiTietKhoHang();
                        ctkh.MaKho = makho;
                        ctkh.MaHangHoa = item.MaHangHoa;
                        ctkh.SoLuong = item.SoLuong.ToString();
                        array.Add(ctkh);
                    }

                }
                Entities.ChiTietKhoHang[] temp = (Entities.ChiTietKhoHang[])array.ToArray(typeof(Entities.ChiTietKhoHang));
                return temp;
            }
            catch
            {
                return new Entities.ChiTietKhoHang[0];
            }
        }

        Entities.TheVip XuLyObjectTheVip(string hanhDong)
        {
            try
            {
                Entities.TheVip thevip = new Entities.TheVip();
                thevip.HanhDong = hanhDong;
                thevip.MaTheVip = hdbanbuon.MaTheVip;
                thevip.Deleted = false;
                thevip.GhiChu = string.Empty;
                double giatriconlai = 0;
                if (Convert.ToDouble(hdbanbuon.TongTienThanhToan) < Convert.ToDouble(hdbanbuon.GiaTriThe))
                {
                    giatriconlai = Convert.ToDouble(hdbanbuon.GiaTriThe) - Convert.ToDouble(hdbanbuon.TongTienThanhToan);
                }
                thevip.GiaTriConLai = giatriconlai.ToString();
                thevip.LoaiThe = "";
                thevip.MaKhachHang = "";
                thevip.TenKhachHang = "";
                thevip.TheVipID = 0;
                return thevip;
            }
            catch
            {
                return null;
            }
        }

        Entities.DiemThuongKhachHang XuLyDiemThuongKhachHang()
        {
            try
            {
                if (tyletinh.Length != 0)
                {
                    double tongthanhtoan = double.Parse(hdbanbuon.ThanhToanNgay);
                    if (tongthanhtoan >= double.Parse(tyletinh[tyletinh.Length - 1].SoTien))
                    {
                        Entities.DiemThuongKhachHang diemthuongkhachhang = TimDiemThuongKhachHang();
                        if (diemthuongkhachhang == null)
                        {
                            diemthuongkhachhang = new Entities.DiemThuongKhachHang();
                            diemthuongkhachhang.Deleted = false;
                            diemthuongkhachhang.DiemDaDung = "0";
                            diemthuongkhachhang.DiemThuongKhachHangID = 0;
                            diemthuongkhachhang.GhiChu = "";
                            diemthuongkhachhang.HanhDong = Common.Constants.Insert;
                            diemthuongkhachhang.MaDiemThuongKhachHang = getIDDiemThuong();
                            diemthuongkhachhang.MaKhachHang = hdbanbuon.MaKhachHang;
                            diemthuongkhachhang.TenKhachHang = hdbanbuon.TenKhachHang;
                            diemthuongkhachhang.TongDiem = (tongthanhtoan / double.Parse(tyletinh[tyletinh.Length - 1].SoTien)).ToString();
                            diemthuongkhachhang.DiemConLai = diemthuongkhachhang.TongDiem;
                            return diemthuongkhachhang;
                        }
                        else
                        {
                            int diemthuonghd = int.Parse(tongthanhtoan.ToString()) / int.Parse(tyletinh[tyletinh.Length - 1].SoTien);
                            diemthuongkhachhang.TongDiem = (double.Parse(diemthuongkhachhang.TongDiem) + diemthuonghd).ToString();
                            diemthuongkhachhang.HanhDong = Common.Constants.Update;
                            return diemthuongkhachhang;
                        }
                    }
                }
                return null;
            }
            catch
            {
                return null;
            }
        }
        #region xử lý id
        public string getIDDiemThuong()
        {
            string str = "";
            Entities.GetID layid = new Entities.GetID();
            layid.TableName = "DiemThuongKhachHang";
            Entities.GetID lay = Common.StaticVariable.InterfaceObject.SelectID(layid);
            if (lay.ColumnName == null)
            {
                return "DTKH_0001";
            }
            str = Common.Utilities.ProcessID(lay.ColumnName);
            return str;
        }
        #endregion
        Entities.DiemThuongKhachHang TimDiemThuongKhachHang()
        {
            try
            {
                foreach (Entities.DiemThuongKhachHang item in this.diemthuongkhachhang)
                {
                    if (item.MaKhachHang == hdbanbuon.MaKhachHang)
                    {
                        return item;
                    }
                }
                return null;
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region Check Conflic Insert
        string mahdbanbuonmoi;
        public bool CheckConflicInsert(Entities.HDBanBuon hdbanle)
        {
            try
            {

                bool kt = CheckID(hdbanle);
                if (kt)
                {
                    mahdbanbuonmoi = getID();
                    return false;
                }
                else
                {

                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        public bool CheckID(Entities.HDBanBuon hd)
        {
            try
            {
                Entities.HDBanBuon[] temp = Common.StaticVariable.InterfaceObject.SelectHDBanBuonID(hd);
                if (temp == null || temp.Length == 0)
                {
                    return false;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region Thẻ Vip
        void TheVip()
        {
            try
            {
                chitiethdbanbuon = (Entities.ChiTietHDBanBuon[])dgvHienThi.DataSource;
                // check object
                if (chitiethdbanbuon == null || chitiethdbanbuon.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG23(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }
                if (dtpHanThanhToan.Text == "" || dtpHanThanhToan.Text == null)
                {
                    MessageBox.Show(Common.MSG.MSG13("Hạn thanh toán"), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    dtpHanThanhToan.Focus();
                    return;
                }
                if (hdbanbuon == null)
                {
                    hdbanbuon = XuLyObject(Common.Constants.Insert);
                    if (hdbanbuon == null)
                    {
                        return;
                    }
                }
                if (hanhDong == Common.Constants.Insert)
                {
                    hdbanbuon.ChietKhau = TinhChietKhau();
                    hdbanbuon.TongTienThanhToan = txtTongTien.Text;
                    hdbanbuon.ThueGTGT = TinhThue();

                }
                frmTheVip xuly = new frmTheVip(hdbanbuon, btnThanhToan.Enabled);
                xuly.ShowDialog();
                if (hanhDong == Common.Constants.Insert)
                {
                    hdbanbuon = frmTheVip.hdbanbuon;
                }
                frmTheVip.hdbanbuon = null;
                if (!frmTheVip.kiemtra)
                {
                    ThanhToan();
                }
                frmTheVip.kiemtra = false;
            }
            catch
            {
            }
            finally
            {
                txtMaHangHoa.Focus();
            }
        }
        #endregion

        #region Thoát
        void Thoat()
        {
            this.Close();
        }
        #endregion

        #region In
        void In(Entities.HDBanBuon hdbanbuon)
        {
            Entities.ChiTietHDBanBuon[] cthdbb = hdbanbuon.ChiTietHDBanBuon;
            int sotang = 0;
            Entities.KhachHang kh = hdbanbuon.KhachHang;

            Entities.BCHoaDonBanBuon[] bc = new Entities.BCHoaDonBanBuon[cthdbb.Length];
            foreach (Entities.ChiTietHDBanBuon item in cthdbb)
            {
                bc[sotang] = new Entities.BCHoaDonBanBuon();
                bc[sotang].ChietKhau = (double.Parse(item.ThanhTien) * (hdbanbuon.PhanTramChietKhauThuongmai) / 100);
                bc[sotang].DonGia = item.DonGia;
                bc[sotang].DonVi = "";
                bc[sotang].MaH = item.MaHangHoa;
                bc[sotang].PTChietKhau = item.PhanTramChietKhau;
                bc[sotang].SoLuong = item.SoLuong.ToString();
                bc[sotang].STT = sotang + 1;
                bc[sotang].TenH = item.TenHangHoa;
                bc[sotang].ThanhTien = double.Parse(item.ThanhTien);
                bc[sotang].ThueGTGT = item.ThueGTGT;
                sotang++;
            }


            BaoCao.frmBaoCaorpt frm = new BaoCao.frmBaoCaorpt(bc, khachhang, hdbanbuon);
            if (frm.kiemtra)
            {
                frm.ShowDialog();
            }
        }
        #endregion

        #region Chiết Khấu Thương Mại
        void ChietKhauThuongMai()
        {
            try
            {
                chitiethdbanbuon = (Entities.ChiTietHDBanBuon[])dgvHienThi.DataSource;
                // check object
                if (chitiethdbanbuon == null || chitiethdbanbuon.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG23(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }
                if (dtpHanThanhToan.Text == "" || dtpHanThanhToan.Text == null)
                {
                    MessageBox.Show(Common.MSG.MSG13("Hạn thanh toán"), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    dtpHanThanhToan.Focus();
                    return;
                }
                if (hdbanbuon == null)
                {
                    hdbanbuon = XuLyObject(Common.Constants.Insert);
                    if (hdbanbuon == null)
                    {
                        return;
                    }
                }


                if (hanhDong != Common.Constants.Update)
                {
                    tienchietkhau = double.Parse(TinhChietKhau());
                    hdbanbuon.ChietKhau = tienchietkhau.ToString();
                    hdbanbuon.TongTienThanhToan = txtTongTien.Text;
                    hdbanbuon.TongTienThanhToan = TongTien();
                    hdbanbuon.ThueGTGT = TinhThue();
                }

                frmChietKhauThuongMai xuly = new frmChietKhauThuongMai(hanhDong, hdbanbuon, btnThanhToan.Enabled, tongtien);
                xuly.ShowDialog();
                if (hanhDong == Common.Constants.Insert)
                {
                    hdbanbuon = frmChietKhauThuongMai.hdbanbuon;
                    tienchietkhauthuongmai = double.Parse(hdbanbuon.ChietKhau);
                    frmChietKhauThuongMai.hdbanbuon = null;
                    //dgvHienThi.DataSource = XuLyChinhSachGiaHangHoa(templv);
                    txtTongTien.Text = Common.Utilities.FormatMoney(Convert.ToString(double.Parse(TongTien()) - tienchietkhauthuongmai));
                    hdbanbuon.TongTienThanhToan = Convert.ToString(double.Parse(TongTien()) - tienchietkhauthuongmai);
                }
                if (!frmChietKhauThuongMai.kiemtra)
                {
                    ThanhToan();
                }
                frmChietKhauThuongMai.kiemtra = false;
            }
            catch
            {
            }
        }
        #endregion

        #region GetID

        private string MaKho = string.Empty;
        private string TenKho = string.Empty;
        private void getKhoHang()
        {
            try
            {
                Entities.CaiDatKho kho = Entitystatic.ViewFile();
                MaKho = kho.MaKho;
                TenKho = kho.TenKho;
            }
            catch { }
        }

        private DateTime ngaythangnam;
        public string getID()
        {
            
            string str = string.Empty;
            try
            {
                ngaythangnam = Entitystatic.date;
                this.getKhoHang();
                str = "HDBB/" + Common.Utilities.GetDateID(this.ngaythangnam.ToString("dd/MM/yyyy")) + "_" + Common.Utilities.ProcessRandomID(Common.Utilities.RandomID());
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                str = "HDBB/" + Common.Utilities.GetDateID(this.ngaythangnam.ToString("dd/MM/yyyy")) + "_" + Common.Utilities.ProcessRandomID(Common.Utilities.RandomID());
            }
            return str;
        }
        #endregion

        #region validate
        public bool Validat()
        {
            try
            {
                if (txtMaKhachHang.Text.Length == 0 || txtMaKhachHang.Text == "<F4 - Tra cứu>")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaKhachHang.Text), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return false;
                }

                if (DateTime.Parse(dtpHanThanhToan.Text).Date < date.Date)
                {
                    MessageBox.Show(Common.MSG.MSG12("Ngày hiện tại", lblHanThanhToan.Text), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return false;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool ValidateDetails()
        {
            try
            {
                if (txtMaHangHoa.Text.Length == 0 || txtMaHangHoa.Text == "<F4 - Tra cứu>")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaHangHoa.Text), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtMaHangHoa.Focus();
                    return false;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        DateTime date;
        Entities.HDBanBuon obj;
        public string mahdbanbuon = "";
        public string manhanvien = "";
        public string tennhanvien = "";
        public string makho = "";
        public string tenkho = "";
        public string mathevip = "";
        public string giatrithe = "0";
        public string phantramchietkhautm = "0";
        public void XuLyDuLieu(Entities.HDBanBuon hdbanbuon)
        {
            try
            {
                mahdbanbuon = hdbanbuon.MaHDBanBuon;
                manhanvien = hdbanbuon.MaNhanVien;
                tennhanvien = hdbanbuon.TenNhanVien;
                makho = hdbanbuon.MaKho;
                tenkho = hdbanbuon.TenKho;
                txtMaKhachHang.Text = hdbanbuon.MaKhachHang;
                txtTenKhachHang.Text = hdbanbuon.TenKhachHang;
                lblNoHienThoi.Text = Common.Utilities.FormatMoney(hdbanbuon.NoHienThoi);
                txtDonDatHang.Text = hdbanbuon.MaDonDatHang;
                txtNguoiNhan.Text = hdbanbuon.NguoiNhanHang;
                date = hdbanbuon.NgayLap;
                mathevip = hdbanbuon.MaTheVip;
                giatrithe = hdbanbuon.GiaTriThe;
                dtpHanThanhToan.Text = hdbanbuon.HanThanhToan.ToShortDateString();
                phantramchietkhautm = hdbanbuon.PhanTramChietKhauThuongmai.ToString();
            }
            catch
            {
            }
        }

        public Entities.HDBanBuon XuLyObject(string hanhDong)
        {
            try
            {
                if (Validat())
                {
                    obj = new Entities.HDBanBuon();
                    obj.HanhDong = hanhDong;
                    obj.MaHDBanBuon = mahdbanbuon;
                    obj.MaKhachHang = txtMaKhachHang.Text;
                    obj.TenKhachHang = txtTenKhachHang.Text;
                    obj.NoHienThoi = lblNoHienThoi.Text;
                    obj.NguoiNhanHang = txtNguoiNhan.Text;
                    obj.HanThanhToan = DateTime.Parse(dtpHanThanhToan.Text);
                    string madondathang = "";
                    if (txtDonDatHang.Text.Length != 0 && txtDonDatHang.Text != "<F4 - Tra cứu>")
                        madondathang = txtDonDatHang.Text;
                    obj.MaDonDatHang = madondathang;
                    obj.MaNhanVien = manhanvien;
                    obj.TenNhanVien = tennhanvien;
                    obj.MaKho = makho;
                    obj.TenKho = tenkho;
                    obj.NgayLap = date.Date;
                    obj.PhanTramChietKhauThuongmai = 0;
                    obj.MaTheVip = mathevip;
                    obj.GiaTriThe = giatrithe;
                    obj.GhiChu = "";
                    obj.Deleted = false;
                    return obj;
                }
                return null;
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region Xử lý list view
        string LayThue(string mathue)
        {
            try
            {
                foreach (Entities.Thue item in thue)
                {
                    if (item.MaThue == mathue)
                    {
                        return item.GiaTriThue;
                    }
                }
                return "0";
            }
            catch
            {
                return "0";
            }
        }

        string TinhThue()
        {
            try
            {
                tongthuegtgt = 0;
                foreach (Entities.ChiTietHDBanBuon item in templv)
                {
                    double thue = double.Parse(item.ThueGTGT);
                    double dongia = double.Parse(item.DonGia);
                    if (hdbanbuon != null)
                    {
                        if (hdbanbuon.PhanTramChietKhauThuongmai != 0)
                        {
                            chietkhauthuongmai = double.Parse(hdbanbuon.PhanTramChietKhauThuongmai.ToString());
                        }
                    }
                    double chietkhau = double.Parse(item.PhanTramChietKhau);
                    int sl = item.SoLuong;
                    double dongiamoi = dongia - ((dongia * chietkhau) / 100);
                    tongthuegtgt += ((dongiamoi * sl) * thue) / 100;
                }
                return (tongthuegtgt).ToString();
            }
            catch
            {
                return "0";
            }
        }

        string TinhChietKhau()
        {
            try
            {
                tienchietkhau = 0;
                foreach (Entities.ChiTietHDBanBuon item in templv)
                {
                    double dongia = double.Parse(item.DonGia);
                    double sl = item.SoLuong;
                    double chietkhau = double.Parse(item.PhanTramChietKhau);
                    tienchietkhau += ((dongia * sl) * chietkhau) / 100;
                }
                return (tienchietkhau).ToString();
            }
            catch
            {
                return "0";
            }
        }

        string TongTien()
        {
            try
            {
                tongtien = 0;
                foreach (Entities.ChiTietHDBanBuon item in templv)
                {
                    tongtien += double.Parse(item.ThanhTien);
                }
                return tongtien.ToString();
            }
            catch
            {
                return "0";
            }
        }
        #endregion

        #region New Row
        void NewRow()
        {
            if (hanhDong != Common.Constants.Insert) return; if (checkDDH) return;
            try
            {
                chietkhauthuongmai = 0;
                if (hdbanbuon != null)
                {
                    if (hdbanbuon.PhanTramChietKhauThuongmai != 0)
                    {
                        chietkhauthuongmai = double.Parse(hdbanbuon.PhanTramChietKhauThuongmai.ToString());
                    }
                }
                string dongiasosanh = Common.Utilities.FormatMoney(dongia).ToString();
                soluong = int.Parse(txtSoLuong.Text);
                int sohangtrongbang;
                hienthi = (Entities.ChiTietHDBanBuon[])dgvHienThi.DataSource;
                // list view = null
                if (hienthi == null)
                {
                    templv = new Entities.ChiTietHDBanBuon[1];
                    dongia = (double.Parse(dongia)).ToString();
                    double dongiadachietkhau = double.Parse(dongia) - ((double.Parse(dongia) * chietkhau) / 100);

                    double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(thuegtgt)) / 100;
                    thanhtien = (dongiadachietkhau + thuegtgtdachietkhau) * soluong;
                    templv[0] = new Entities.ChiTietHDBanBuon(Common.Constants.Insert, mahdbanbuon, txtMaHangHoa.Text, txtTenHangHoa.Text,
                        soluong, Common.Utilities.FormatMoney(dongia),
                        chietkhau.ToString(), thuegtgt,
                        Common.Utilities.FormatMoney(thanhtien.ToString()), "", false, khuyenmai);
                    dgvHienThi.DataSource = templv;
                    fix();
                    return;
                }

                sohangtrongbang = hienthi.Length;
                // số lượng bảng ghi khác 0
                if (sohangtrongbang != 0)
                {
                    for (int j = 0; j < sohangtrongbang; j++)
                    {
                        // nếu tìm được mã đã có trong list view
                        if (mahanghoa.ToUpper() == hienthi[j].MaHangHoa.ToUpper() && dongiasosanh == hienthi[j].DonGia)
                        {
                            templv = new Entities.ChiTietHDBanBuon[sohangtrongbang];
                            break;
                        }
                        // nếu không tìm được
                        else
                            templv = new Entities.ChiTietHDBanBuon[sohangtrongbang + 1];
                    }
                }
                // số lượng bảng ghi = 0
                else
                    templv = new Entities.ChiTietHDBanBuon[sohangtrongbang + 1];
                // nếu số lượng bảng ghi khác 0
                if (templv.Length != 0)
                {
                    try
                    {
                        // số lượng bảng ghi = số lượng row list view
                        if (templv.Length == hienthi.Length)
                        {
                            SoLuongBangSoLuong(templv, hienthi);
                        }
                        // số lượng bảng ghi không = số lượng row list view
                        else
                        {
                            SoLuongKhacSoLuong(templv, hienthi);
                        }
                    }
                    catch (Exception ex)
                    {
                        dongia = (double.Parse(dongia)).ToString();
                        double dongiadachietkhau = double.Parse(dongia) - ((double.Parse(dongia) * (chietkhau + chietkhauthuongmai)) / 100);
                        double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(thuegtgt)) / 100;
                        thanhtien = ((dongiadachietkhau + thuegtgtdachietkhau) * soluong);

                        templv[templv.Length - 1] = new Entities.ChiTietHDBanBuon(Common.Constants.Insert, mahdbanbuon, txtMaHangHoa.Text, txtTenHangHoa.Text,
                                            soluong, Common.Utilities.FormatMoney(dongia), chietkhau.ToString(), thuegtgt,
                                            Common.Utilities.FormatMoney(thanhtien.ToString()), "", false, khuyenmai);
                    }
                    dgvHienThi.DataSource = templv;
                }
            }
            catch
            {
                return;
            }
            finally
            {
                soluong = 1;
                mahanghoa = "";
                khuyenmai = false;
                txtMaHangHoa.Text = "";
                txtTenHangHoa.Text = "";
                txtMaHangHoa.Focus();
                dongia = "0";
                txtDonGia.Text = dongia;
                chietkhau = 0;
                thuegtgt = "0";
                thanhtien = 0;
                dgvHienThi.DataSource = XuLyChinhSachGiaHangHoa(templv);
                fix();
                txtTongTien.Text = Common.Utilities.FormatMoney(TongTien());
            }
        }

        void SoLuongBangSoLuong(Entities.ChiTietHDBanBuon[] templv, Entities.ChiTietHDBanBuon[] hienthi)
        {
            for (int j = 0; j < templv.Length; j++)
            {
                string dongiasosanh = Common.Utilities.FormatMoney(dongia).ToString();
                // nếu mã = mã trong list view
                if (mahanghoa.ToUpper() == hienthi[j].MaHangHoa.ToUpper() && dongiasosanh == hienthi[j].DonGia)
                {
                    int soluongcu = hienthi[j].SoLuong;
                    int soluonghientai = soluongcu + soluong;
                    dongia = (double.Parse(dongia)).ToString();
                    double dongiadachietkhau = double.Parse(dongia) - ((double.Parse(dongia) * (chietkhau + chietkhauthuongmai)) / 100);
                    double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(thuegtgt)) / 100;
                    thanhtien = ((dongiadachietkhau + thuegtgtdachietkhau) * soluonghientai);

                    templv[j] = new Entities.ChiTietHDBanBuon(Common.Constants.Insert, mahdbanbuon, mahanghoa.ToUpper(), txtTenHangHoa.Text,
                            soluonghientai,
                            Common.Utilities.FormatMoney(dongia), chietkhau.ToString(), thuegtgt,
                            Common.Utilities.FormatMoney(thanhtien.ToString()), "", false, khuyenmai);

                }
                // nếu mã không = mã trong list view
                else
                    templv[j] = new Entities.ChiTietHDBanBuon(Common.Constants.Insert, mahdbanbuon, hienthi[j].MaHangHoa.ToUpper(), hienthi[j].TenHangHoa,
                 hienthi[j].SoLuong, hienthi[j].DonGia, hienthi[j].PhanTramChietKhau, hienthi[j].ThueGTGT, hienthi[j].ThanhTien, "", false, hienthi[j].KhuyenMai);

            }
        }

        void SoLuongKhacSoLuong(Entities.ChiTietHDBanBuon[] templv, Entities.ChiTietHDBanBuon[] hienthi)
        {
            for (int j = 0; j < templv.Length; j++)
            {

                // lấy lại số bảng ghi trên list view
                if (j < templv.Length - 1)
                    templv[j] = new Entities.ChiTietHDBanBuon(Common.Constants.Insert, mahdbanbuon, hienthi[j].MaHangHoa.ToUpper(), hienthi[j].TenHangHoa,
                 hienthi[j].SoLuong, hienthi[j].DonGia, hienthi[j].PhanTramChietKhau, hienthi[j].ThueGTGT, hienthi[j].ThanhTien, "", false, hienthi[j].KhuyenMai);
                // bảng ghi cuối cùng là mới insert vào
                else
                {
                    dongia = (double.Parse(dongia)).ToString();
                    double dongiadachietkhau = double.Parse(dongia) - ((double.Parse(dongia) * (chietkhau + chietkhauthuongmai)) / 100);
                    double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(thuegtgt)) / 100;
                    thanhtien = ((dongiadachietkhau + thuegtgtdachietkhau) * soluong);
                    templv[templv.Length - 1] = new Entities.ChiTietHDBanBuon(Common.Constants.Insert, mahdbanbuon, txtMaHangHoa.Text, txtTenHangHoa.Text,
                            soluong,
                            Common.Utilities.FormatMoney(dongia), chietkhau.ToString(), thuegtgt,
                            Common.Utilities.FormatMoney(thanhtien.ToString()), "", false, khuyenmai);
                }

            }
        }


        void AddRowMang()
        {
            try
            {
                bool kt = false;
                foreach (Entities.HangHoa item in manghanghoa)
                {
                    if (!kt)
                    {
                        mahanghoa = item.MaHangHoa.ToUpper();
                        txtMaHangHoa.Text = item.MaHangHoa.ToUpper();
                        txtTenHangHoa.Text = item.TenHangHoa;
                        thuegtgt = LayThue(item.MaThue);
                        dongia = item.GiaBanBuon;
                        txtDonGia.Text = dongia;
                        soluong = item.SoLuong;
                        khuyenmai = true;
                        kt = true;
                    }
                    else
                    {
                        mahanghoa = item.MaHangHoa.ToUpper();
                        txtMaHangHoa.Text = item.MaHangHoa.ToUpper();
                        txtTenHangHoa.Text = item.TenHangHoa;
                        thuegtgt = "0";
                        dongia = "0";
                        txtDonGia.Text = dongia;
                        chietkhau = 0;
                        soluong = item.SoLuong;
                    }
                    NewRow();
                }
            }
            catch
            {
            }
        }

        #endregion

        #region Sửa Hàng Hóa
        void SuaHangHoa()
        {
            if (hanhDong != Common.Constants.Insert) return; if (checkDDH) return;
            save = ((Entities.ChiTietHDBanBuon[])dgvHienThi.DataSource)[i];
            if (save == null)
            {
                MessageBox.Show(Common.MSG.MSG45(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                return;
            }
            try
            {

                if (save.DonGia == "0")
                {
                    MessageBox.Show(Common.MSG.MSG25(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }
                frmNhapSoLuong frm = new frmNhapSoLuong();
                frm.ShowDialog();
                if (frmNhapSoLuong.soluong == 0)
                {
                    return;
                }
                soluong = frmNhapSoLuong.soluong;
                frmNhapSoLuong.soluong = 0;
                hienthi = (Entities.ChiTietHDBanBuon[])dgvHienThi.DataSource;
                // list view = null
                if (hienthi == null)
                {
                    return;
                }
                if (save.KhuyenMai)
                {
                    Entities.ChiTietHDBanBuon temp = save;
                    SuaHangHoaKhuyenMai(temp, soluong);
                }
                else
                {
                    SuaHangHoaKhongKhuyenMai();
                }
            }
            catch
            {
            }
            finally
            {
                save = null;
                txtMaHangHoa.Focus();
                dgvHienThi.DataSource = XuLyChinhSachGiaHangHoa(templv);
                fix();
                txtTongTien.Text = Common.Utilities.FormatMoney(TongTien());
            }
        }

        void SuaHangHoaKhongKhuyenMai()
        {
            try
            {
                templv = new Entities.ChiTietHDBanBuon[hienthi.Length];
                int sotang = 0;
                for (int j = 0; j < hienthi.Length; j++)
                {
                    if (hienthi[j].MaHangHoa.ToUpper() != save.MaHangHoa.ToUpper())
                    {
                        templv[sotang] = new Entities.ChiTietHDBanBuon(Common.Constants.Insert, mahdbanbuon, hienthi[j].MaHangHoa.ToUpper(), hienthi[j].TenHangHoa,
                                 hienthi[j].SoLuong, hienthi[j].DonGia, hienthi[j].PhanTramChietKhau, hienthi[j].ThueGTGT, hienthi[j].ThanhTien, "", false, hienthi[j].KhuyenMai);
                        sotang++;
                    }
                    else
                    {
                        dongia = hienthi[j].DonGia;
                        chietkhau = int.Parse(hienthi[j].PhanTramChietKhau);
                        thuegtgt = hienthi[j].ThueGTGT;
                        double dongiadachietkhau = double.Parse(dongia) - ((double.Parse(dongia) * chietkhau) / 100);
                        double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(thuegtgt)) / 100;
                        thanhtien = (dongiadachietkhau + thuegtgtdachietkhau) * soluong;
                        templv[sotang] = new Entities.ChiTietHDBanBuon(Common.Constants.Insert, mahdbanbuon, hienthi[j].MaHangHoa.ToUpper(), hienthi[j].TenHangHoa,
                                 soluong, hienthi[j].DonGia, hienthi[j].PhanTramChietKhau, hienthi[j].ThueGTGT, thanhtien.ToString(), "", false, hienthi[j].KhuyenMai);
                        sotang++;
                    }
                }
                dgvHienThi.DataSource = templv;
                fix();
                save = null;
            }
            catch
            {
            }
            finally
            {
                txtTongTien.Text = Common.Utilities.FormatMoney(TongTien());
                soluong = 1;
                khuyenmai = false;
                dongia = "0";
                txtDonGia.Text = dongia;
                chietkhau = 0;
                thuegtgt = "0";
                thanhtien = 0;
            }
        }

        void SuaHangHoaKhuyenMai(Entities.ChiTietHDBanBuon save, int soluog)
        {
            try
            {
                dgvHienThi.DataSource = null;
                ArrayList list = new ArrayList();
                foreach (Entities.ChiTietHDBanBuon item in hienthi)
                {
                    if (item.KhuyenMai)
                    {

                        if (item.MaHangHoa.ToUpper() != save.MaHangHoa.ToUpper())
                        {
                            mahanghoa = item.MaHangHoa.ToUpper();
                            soluong = item.SoLuong;
                            manghanghoa = CheckSuaHangHoaKhuyenMai();
                            if (manghanghoa.Length != 0)
                            {
                                SuaHangHoaTheoMang();
                            }
                        }
                        else
                        {
                            mahanghoa = item.MaHangHoa.ToUpper();
                            soluong = soluog;
                            manghanghoa = CheckSuaHangHoaKhuyenMai();
                            if (manghanghoa.Length != 0)
                            {
                                SuaHangHoaTheoMang();
                            }

                        }
                    }
                    else
                    {
                        if (item.DonGia != "0")
                        {
                            mahanghoa = item.MaHangHoa.ToUpper();
                            txtMaHangHoa.Text = item.MaHangHoa.ToUpper();
                            txtTenHangHoa.Text = item.TenHangHoa;
                            thuegtgt = LayThue(item.ThueGTGT);
                            dongia = item.DonGia;
                            txtDonGia.Text = dongia;
                            soluong = item.SoLuong;
                            khuyenmai = item.KhuyenMai;
                            NewRow();
                        }
                    }
                }
            }
            catch
            {
            }
            finally
            {
                manghanghoa = null;
                txtMaHangHoa.Focus();
            }
        }

        Entities.HangHoa[] CheckSuaHangHoaKhuyenMai()
        {
            try
            {

                ArrayList array = new ArrayList();
                bool kt = false;
                foreach (Entities.ChiTietKhuyenMaiTangHang item in ctkmth)
                {

                    if (item.MaHangKhuyenMai.ToUpper() == mahanghoa.ToUpper())
                    {
                        khuyenmai = true;
                        if (item.SoLuongKhuyenMai <= soluong)
                        {
                            tyle = soluong / item.SoLuongKhuyenMai;
                            if (item.MaHangDuocKhuyenmai == item.MaHangKhuyenMai)
                            {
                                Entities.HangHoa hh;
                                // hàng khuyến mại
                                int soluongdu = soluong - (item.SoLuongKhuyenMai * tyle);
                                hh = LayHangHoa(item.MaHangKhuyenMai.ToUpper(), (item.SoLuongKhuyenMai * tyle) + soluongdu, true);
                                mahanghoa = hh.MaHangHoa.ToUpper();
                                txtMaHangHoa.Text = hh.MaHangHoa.ToUpper();
                                txtTenHangHoa.Text = hh.TenHangHoa;
                                thuegtgt = LayThue(hh.MaThue);
                                dongia = hh.GiaBanBuon;
                                txtDonGia.Text = dongia;
                                soluong = hh.SoLuong;
                                khuyenmai = hh.KhuyenMai;
                                NewRow();

                                // hàng được KM
                                hh = LayHangHoa(item.MaHangDuocKhuyenmai.ToUpper(), item.SoLuongDuocKhuyenMai * tyle, false);
                                mahanghoa = hh.MaHangHoa.ToUpper();
                                txtMaHangHoa.Text = hh.MaHangHoa.ToUpper();
                                txtTenHangHoa.Text = hh.TenHangHoa;
                                thuegtgt = "0";
                                dongia = "0";
                                txtDonGia.Text = dongia;
                                chietkhau = 0;
                                soluong = hh.SoLuong;
                                khuyenmai = hh.KhuyenMai;
                                NewRow();
                            }
                            else
                            {
                                if (!kt)
                                {
                                    int soluongdu = soluong - (item.SoLuongKhuyenMai * tyle);
                                    array.Add(LayHangHoa(item.MaHangKhuyenMai, (item.SoLuongKhuyenMai * tyle) + soluongdu, true));
                                    array.Add(LayHangHoa(item.MaHangDuocKhuyenmai, item.SoLuongDuocKhuyenMai * tyle, false));
                                    kt = true;
                                }
                                else
                                    array.Add(LayHangHoa(item.MaHangDuocKhuyenmai, item.SoLuongDuocKhuyenMai * tyle, false));
                            }
                        }
                        else
                        {
                            Entities.HangHoa hh;
                            // hàng khuyến mại
                            hh = LayHangHoa(item.MaHangKhuyenMai.ToUpper(), soluong, true);
                            mahanghoa = hh.MaHangHoa.ToUpper();
                            txtMaHangHoa.Text = hh.MaHangHoa.ToUpper();
                            txtTenHangHoa.Text = hh.TenHangHoa;
                            thuegtgt = LayThue(hh.MaThue);
                            dongia = hh.GiaBanBuon;
                            txtDonGia.Text = dongia;
                            soluong = hh.SoLuong;
                            khuyenmai = hh.KhuyenMai;
                            NewRow();
                        }
                    }
                }
                manghanghoa = (Entities.HangHoa[])array.ToArray(typeof(Entities.HangHoa));
                return manghanghoa;
            }
            catch
            {
                return new Entities.HangHoa[0];
            }
        }

        void SuaHangHoaTheoMang()
        {
            try
            {
                foreach (Entities.HangHoa item in manghanghoa)
                {

                    if (item.KhuyenMai)
                    {
                        mahanghoa = item.MaHangHoa.ToUpper();
                        txtMaHangHoa.Text = item.MaHangHoa.ToUpper();
                        txtTenHangHoa.Text = item.TenHangHoa;
                        thuegtgt = LayThue(item.MaThue);
                        dongia = item.GiaBanBuon;
                        txtDonGia.Text = dongia;
                        soluong = item.SoLuong;
                        khuyenmai = item.KhuyenMai;
                    }
                    else
                    {
                        mahanghoa = item.MaHangHoa.ToUpper();
                        txtMaHangHoa.Text = item.MaHangHoa.ToUpper();
                        txtTenHangHoa.Text = item.TenHangHoa;
                        thuegtgt = "0";
                        dongia = "0";
                        txtDonGia.Text = dongia;
                        chietkhau = 0;
                        soluong = item.SoLuong;
                        khuyenmai = item.KhuyenMai;
                    }
                    NewRow();
                }
            }
            catch
            {
            }
            finally
            {
                txtMaHangHoa.Focus();
            }
        }
        #endregion

        #region Xóa Hàng Hóa
        void XoaHangHoa()
        {
            if (hanhDong != Common.Constants.Insert) return; if (checkDDH) return;
            save = ((Entities.ChiTietHDBanBuon[])dgvHienThi.DataSource)[i];
            if (save == null)
            {
                MessageBox.Show(Common.MSG.MSG42(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                return;
            }
            try
            {
                hienthi = (Entities.ChiTietHDBanBuon[])dgvHienThi.DataSource;
                // list view = null
                if (hienthi == null)
                {
                    return;
                }

                if (save.DonGia == "0")
                {
                    MessageBox.Show(Common.MSG.MSG26(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }
                if (save.KhuyenMai)
                {
                    Entities.ChiTietHDBanBuon temp = save;
                    XoaHangHoaKhuyenMai(temp);
                }
                else
                {
                    XoaHangHoaKhongKhuyenMai();
                }
            }
            catch
            {
            }
            finally
            {
                save = null;
                txtMaHangHoa.Focus();
                dgvHienThi.DataSource = XuLyChinhSachGiaHangHoa(templv);
                fix();
                txtTongTien.Text = Common.Utilities.FormatMoney(TongTien());
            }
        }

        void XoaHangHoaKhuyenMai(Entities.ChiTietHDBanBuon save)
        {
            hienthi = (Entities.ChiTietHDBanBuon[])dgvHienThi.DataSource;
            try
            {
                bool kt = false;
                dgvHienThi.DataSource = null;
                ArrayList list = new ArrayList();
                foreach (Entities.ChiTietHDBanBuon item in hienthi)
                {
                    if (item.MaHangHoa.ToUpper() != save.MaHangHoa.ToUpper())
                    {
                        if (item.KhuyenMai)
                        {
                            mahanghoa = item.MaHangHoa.ToUpper();
                            soluong = item.SoLuong;
                            manghanghoa = CheckSuaHangHoaKhuyenMai();
                            XoaHangHoaTheoMang();
                            kt = true;
                        }
                        if (item.KhuyenMai == false)
                        {
                            if (item.DonGia != "0")
                            {
                                mahanghoa = item.MaHangHoa.ToUpper();
                                txtMaHangHoa.Text = item.MaHangHoa.ToUpper();
                                txtTenHangHoa.Text = item.TenHangHoa;
                                thuegtgt = LayThue(item.ThueGTGT);
                                dongia = item.DonGia;
                                txtDonGia.Text = dongia;
                                soluong = item.SoLuong;
                                khuyenmai = item.KhuyenMai;
                                NewRow();
                                kt = true;
                            }
                        }
                    }
                }
                if (!kt)
                {
                    templv = new Entities.ChiTietHDBanBuon[0];
                    dgvHienThi.DataSource = templv;
                    fix();
                }
            }
            catch
            {
            }
            finally
            {
                manghanghoa = null;
                txtMaHangHoa.Focus();
            }
        }

        void XoaHangHoaTheoMang()
        {
            try
            {
                foreach (Entities.HangHoa item in manghanghoa)
                {

                    if (item.KhuyenMai)
                    {
                        mahanghoa = item.MaHangHoa.ToUpper();
                        txtMaHangHoa.Text = item.MaHangHoa.ToUpper();
                        txtTenHangHoa.Text = item.TenHangHoa;
                        thuegtgt = LayThue(item.MaThue);
                        dongia = item.GiaBanBuon;
                        txtDonGia.Text = dongia;
                        soluong = item.SoLuong;
                        khuyenmai = item.KhuyenMai;
                    }
                    else
                    {
                        mahanghoa = item.MaHangHoa.ToUpper();
                        txtMaHangHoa.Text = item.MaHangHoa.ToUpper();
                        txtTenHangHoa.Text = item.TenHangHoa;
                        thuegtgt = "0";
                        dongia = "0";
                        txtDonGia.Text = dongia;
                        chietkhau = 0;
                        soluong = item.SoLuong;
                        khuyenmai = item.KhuyenMai;
                    }
                    NewRow();
                }
            }
            catch
            {
            }
            finally
            {
                txtMaHangHoa.Focus();

            }
        }

        void XoaHangHoaKhongKhuyenMai()
        {
            try
            {
                templv = new Entities.ChiTietHDBanBuon[hienthi.Length - 1];
                int sotang = 0;
                for (int j = 0; j < hienthi.Length; j++)
                {
                    if (hienthi[j].MaHangHoa.ToUpper() != save.MaHangHoa.ToUpper() || hienthi[j].DonGia != save.DonGia)
                    {
                        templv[sotang] = new Entities.ChiTietHDBanBuon(Common.Constants.Insert, mahdbanbuon, hienthi[j].MaHangHoa.ToUpper(), hienthi[j].TenHangHoa,
                                 hienthi[j].SoLuong, hienthi[j].DonGia, hienthi[j].PhanTramChietKhau, hienthi[j].ThueGTGT, hienthi[j].ThanhTien, "", false, hienthi[j].KhuyenMai);
                        sotang++;
                    }
                }
                dgvHienThi.DataSource = templv;
                fix();
                save = null;
            }
            catch
            {
            }
            finally
            {
                txtTongTien.Text = Common.Utilities.FormatMoney(TongTien());
                txtMaHangHoa.Focus();
            }
        }
        #endregion

        #region Thêm Hàng Hóa
        void ThemHangHoa()
        {
            if (hanhDong != Common.Constants.Insert) return; if (checkDDH) return;
            try
            {
                if (makho.Length == 0 || makho == "NULL")
                {
                    MessageBox.Show(Common.MSG.MSG28(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }
                if (txtMaKhachHang.Text == "<F4 - Tra cứu>")
                {
                    MessageBox.Show(Common.MSG.MSG13("Khách hàng"), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }
                Entities.KhoHang kh = new Entities.KhoHang();
                kh.MaKho = makho;
                TimKiem.frmHangHoa timkiem = new TimKiem.frmHangHoa(kh);
                timkiem.ShowDialog();
                if (TimKiem.frmHangHoa.selectedItem != null)
                {
                    txtMaHangHoa.Text = TimKiem.frmHangHoa.selectedItem.MaHangHoa.ToUpper();
                    txtTenHangHoa.Text = TimKiem.frmHangHoa.selectedItem.TenHangHoa;
                    thuegtgt = LayThue(TimKiem.frmHangHoa.selectedItem.MaThue);
                    dongia = TimKiem.frmHangHoa.selectedItem.GiaBanBuon;
                    txtDonGia.Text = dongia;
                    TimKiem.frmHangHoa.selectedItem = null;
                    txtSoLuong.Focus();
                }
            }
            catch
            {
            }
            finally
            {

            }
        }
        #endregion

        #region Thêm khách hàng
        void ThemKhachHang()
        {
            if (hanhDong != Common.Constants.Insert) return;

            if (txtMaKhachHang.Text != "<F4 - Tra cứu>")
            {
                if (MessageBox.Show(Common.MSG.MSG43(), Common.MSG.TieuDe, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {

                    txtMaKhachHang.Text = "<F4 - Tra cứu>";
                    lblNoHienThoi.Text = "";
                    dgvHienThi.DataSource = new Entities.ChiTietHDBanBuon[0];
                    fix();
                    txtDonDatHang.Text = "";
                    checkDDH = false;
                    txtNguoiNhan.Focus();
                    return;
                }
                else
                    return;
            }
            try
            {
                TimKiem.frmKhachHang frm = new TimKiem.frmKhachHang();
                frm.ShowDialog();
                if (TimKiem.frmKhachHang.khachhang != null)
                {
                    txtMaKhachHang.Text = TimKiem.frmKhachHang.khachhang.MaKhachHang;
                    txtTenKhachHang.Text = TimKiem.frmKhachHang.khachhang.Ten;
                    lblNoHienThoi.Text = Common.Utilities.FormatMoney(TimKiem.frmKhachHang.khachhang.DuNo);
                    khachhang = TimKiem.frmKhachHang.khachhang;
                    TimKiem.frmKhachHang.khachhang = null;
                    txtNguoiNhan.Focus();
                }
            }
            catch
            {
            }
        }
        #endregion

        #region Thêm Đơn Đặt hàng Khách hàng
        void ThemDDHKhachHang()
        {
            if (hanhDong != Common.Constants.Insert) return;
            if (txtMaKhachHang.Text == "<F4 - Tra cứu>")
            {
                MessageBox.Show(Common.MSG.MSG13("Khách hàng"), Common.MSG.TieuDe, MessageBoxButtons.OK);
                return;
            }
            if (checkDDH)
            {
                if (MessageBox.Show(Common.MSG.MSG44(), Common.MSG.TieuDe, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    dgvHienThi.DataSource = new Entities.ChiTietHDBanBuon[0];
                    fix();
                    templv = new Entities.ChiTietHDBanBuon[0];
                    chitiethdbanbuon = new Entities.ChiTietHDBanBuon[0];
                    txtMaHangHoa.Text = "<F4 - Tra cứu>";
                    txtDonDatHang.Text = "<F4 - Tra cứu>";
                    checkDDH = false;
                    txtTongTien.Text = "0";
                    return;
                }
                else
                    return;

            }
            try
            {
                TimKiem.frmDonDatHangKH frm = new TimKiem.frmDonDatHangKH(txtMaKhachHang.Text);
                frm.ShowDialog();
                if (TimKiem.frmDonDatHangKH.dondathangkh != null)
                {
                    txtDonDatHang.Text = TimKiem.frmDonDatHangKH.dondathangkh.MaDonDatHangKH;
                    dondathangkh = TimKiem.frmDonDatHangKH.dondathangkh;
                    chitietdondathangkh = Common.StaticVariable.InterfaceObject.SelectChiTietDonHangKH(dondathangkh.MaDonDatHangKH);
                    ArrayList array = new ArrayList();
                    foreach (Entities.ChiTietDonHangKH item in chitietdondathangkh)
                    {
                        Entities.ChiTietHDBanBuon temp = new Entities.ChiTietHDBanBuon();
                        temp.Deleted = false;
                        temp.DonGia = item.Gia;
                        temp.GhiChu = item.GhiChu;
                        temp.HanhDong = Common.Constants.Insert;
                        temp.KhuyenMai = false;
                        temp.MaHangHoa = item.MaHangHoa.ToUpper();
                        temp.MaHDBanBuon = mahdbanbuon;
                        temp.PhanTramChietKhau = item.PTKhuyenMai;
                        temp.SoLuong = int.Parse(string.Format("{0:0}", double.Parse(item.SoLuong.ToString())));
                        temp.SoLuongConlai = int.Parse(string.Format("{0:0}", double.Parse(item.SoLuong.ToString())));
                        temp.TenHangHoa = item.TenHangHoa;
                        temp.ThanhTien = item.TongTien;
                        temp.ThueGTGT = item.Thue;
                        array.Add(temp);
                    }
                    checkDDH = true;
                    TimKiem.frmDonDatHangKH.dondathangkh = null;
                    txtNguoiNhan.Focus();
                    templv = (Entities.ChiTietHDBanBuon[])array.ToArray(typeof(Entities.ChiTietHDBanBuon));

                    dgvHienThi.DataSource = templv;
                    fix();

                    txtTongTien.Text = Common.Utilities.FormatMoney(TongTien());
                }
            }
            catch
            {
            }
        }
        #endregion

        #region Event
        private void frmXuLy_Load(object sender, EventArgs e)
        {
            lblTenNhanVien.Text = UtilitiesVariable.User.TenDangNhap;
            this.FormClosing += new FormClosingEventHandler(frmXuLy_FormClosing);
            btnCKTM.Click += new EventHandler(btnCKTM_Click);
            btnThanhToan.Click += new EventHandler(btnThanhToan_Click);
            btnThemGV.Click += new EventHandler(btnThemGV_Click);
            btnTheVip.Click += new EventHandler(btnTheVip_Click);
            btnThoat.Click += new EventHandler(btnThoat_Click);
            btnTimDDH.Click += new EventHandler(btnTimDDH_Click);
            btnTimKH.Click += new EventHandler(btnTimKH_Click);
            dgvHienThi.CellClick += new DataGridViewCellEventHandler(dgvHienThi_CellClick);
            dgvHienThi.CellDoubleClick += new DataGridViewCellEventHandler(dgvHienThi_CellDoubleClick);
            dgvHienThi.KeyDown += new KeyEventHandler(dgvHienThi_KeyDown);
            txtMaHangHoa.KeyDown += new KeyEventHandler(txt_KeyDown);
            txtSoLuong.KeyDown += new KeyEventHandler(txt_KeyDown);
            txtMaKhachHang.KeyDown += new KeyEventHandler(txt_KeyDown);
            txtDonDatHang.KeyDown += new KeyEventHandler(txt_KeyDown);
            templv = new Entities.ChiTietHDBanBuon[0];
            dgvHienThi.DataSource = templv;
            fix();
        }

        void dgvHienThi_KeyDown(object sender, KeyEventArgs e)
        {
            if (hanhDong != Common.Constants.Insert)
                return;
            if (checkDDH)
                return;
            if (i < 0)
                return;
            if (dgvHienThi.RowCount == 0)
                return;
            save = ((Entities.ChiTietHDBanBuon[])dgvHienThi.DataSource)[i];
            
            switch (e.KeyData)
            {
                case Keys.Enter:
                    {
                        SuaHangHoa();
                        break;
                    }
                case Keys.Delete:
                    {
                        XoaHangHoa();
                        break;
                    }
            }
        }

        void txt_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                switch (e.KeyData)
                {
                    case Keys.F4:
                        {
                            TextBox tx = (TextBox)sender;
                            switch (tx.Name)
                            {
                                case "txtMaHangHoa":
                                    {
                                        ThemHangHoa();
                                        break;
                                    }
                                case "txtMaKhachHang":
                                    {
                                        ThemKhachHang();
                                        break;
                                    }
                                case "txtDonDatHang":
                                    {
                                        ThemDDHKhachHang();
                                        break;
                                    }
                            }
                            break;
                        }
                    case Keys.Enter:
                        {
                            TextBox tx = (TextBox)sender;
                            switch (tx.Name)
                            {
                                case "txtSoLuong":
                                    {
                                        XuLy_Enter();
                                        break;
                                    }
                                case "txtMaHangHoa":
                                    {
                                        txtSoLuong.Focus();
                                        txtSoLuong.SelectAll();
                                        break;
                                    }
                                case "txtMaKhachHang":
                                    {
                                        txtNguoiNhan.Focus();
                                        break;
                                    }
                            }
                            break;
                        }
                    case Keys.Up:
                        {
                            XuLyKeyUp();
                            break;
                        }
                    case Keys.Down:
                        {
                            XuLyKeyDown();
                            break;
                        }
                }
            }
            catch
            {
            }
        }

        void dgvHienThi_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            SuaHangHoa();
        }

        void dgvHienThi_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (hanhDong != Common.Constants.Insert)
                return;
            if (checkDDH)
                return;
            try
            {
                i = e.RowIndex;
                if (i < 0)
                    return;
                if (dgvHienThi.RowCount == 0)
                    return;
                save = ((Entities.ChiTietHDBanBuon[])dgvHienThi.DataSource)[i];
            }
            catch
            {
            }

        }

        void btnTimKH_Click(object sender, EventArgs e)
        {
            ThemKhachHang();
        }

        void btnTimDDH_Click(object sender, EventArgs e)
        {
            ThemDDHKhachHang();
        }

        void btnTheVip_Click(object sender, EventArgs e)
        {
            TheVip();
        }

        void btnThemGV_Click(object sender, EventArgs e)
        {
            XuLy_Enter();
        }

        void btnThanhToan_Click(object sender, EventArgs e)
        {
            ThanhToan();
        }

        void btnCKTM_Click(object sender, EventArgs e)
        {
            ChietKhauThuongMai();
        }

        void txtTyLeTinh_TextChanged(object sender, EventArgs e)
        {
            TextBox temp = (TextBox)sender;
            int vt = temp.SelectionStart;
            string str = new string(temp.Text.ToList<char>().Where(c => char.IsNumber(c)).ToArray<char>());

            temp.Text = str;

            temp.SelectionStart = vt;
        }

        void btnThoat_Click(object sender, EventArgs e)
        {
            Thoat();
        }

        void frmXuLy_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!checkClose)
                if (MessageBox.Show(Common.MSG.MSG2(), Common.MSG.TieuDe, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    e.Cancel = checkClose;
                else
                    e.Cancel = !checkClose;
            else
            {
                GetData(kiemtra);
            }
        }

        #region xử lý tiền tệ
        void XuLyTienTe()
        {
        }
        #endregion

        #region xử lý chính sách giá khuyến mại
        Entities.ChiTietChinhSachGiaHangHoa[] ctcsghh;
        Entities.ChiTietChinhSachGiaHangHoa[] CheckChinhSachGiaHangHoa()
        {
            try
            {
                if (chinhsachgiahanghoa == null)
                    chinhsachgiahanghoa = new KhuyenMaiHangHoa.frmQuanLy().HienThi(date);
                if (chitietchinhsachgiahanghoa == null)
                    chitietchinhsachgiahanghoa = HienThiCTCSGHH();
                ArrayList array = new ArrayList();
                foreach (Entities.ChinhSachGiaHangHoa item in chinhsachgiahanghoa)
                {
                    if (item.GiaTriTrangThai == "Đang sử dụng")
                    {
                        array.Add(item);
                    }
                }
                Entities.ChinhSachGiaHangHoa[] csghh = (Entities.ChinhSachGiaHangHoa[])array.ToArray(typeof(Entities.ChinhSachGiaHangHoa));

                array = new ArrayList();
                foreach (Entities.ChinhSachGiaHangHoa item in csghh)
                {
                    foreach (Entities.ChiTietChinhSachGiaHangHoa item1 in chitietchinhsachgiahanghoa)
                    {
                        if (item.MaChinhSachGiaHangHoa == item1.MaChinhSachGiaHangHoa)
                        {
                            array.Add(item1);
                        }
                    }
                }
                ctcsghh = (Entities.ChiTietChinhSachGiaHangHoa[])array.ToArray(typeof(Entities.ChiTietChinhSachGiaHangHoa));
                return ctcsghh;
            }
            catch
            {
                return new Entities.ChiTietChinhSachGiaHangHoa[0];
            }
        }

        public Entities.ChiTietChinhSachGiaHangHoa[] HienThiCTCSGHH()
        {
            try
            {
                Entities.ChiTietChinhSachGiaHangHoa[] chitietchinhsachgiahang = Common.StaticVariable.InterfaceObject.SelectChiTietChinhSachGiaHangHoa();
                return chitietchinhsachgiahang;
            }
            catch { return new Entities.ChiTietChinhSachGiaHangHoa[0]; }
        }

        bool ChinhSachGiaHangHoa()
        {
            try
            {
                ctcsghh = CheckChinhSachGiaHangHoa();
                if (ctcsghh.Length == 0)
                    return false;

                return true;
            }
            catch
            {
                return false;
            }
        }

        Entities.ChiTietHDBanBuon[] XuLyChinhSachGiaHangHoa(Entities.ChiTietHDBanBuon[] chitiethdbanle)
        {
            try
            {
                ArrayList array = new ArrayList();
                if (ChinhSachGiaHangHoa())
                {
                    foreach (Entities.ChiTietHDBanBuon item in chitiethdbanle)
                    {
                        bool kt = false;
                        foreach (Entities.ChiTietChinhSachGiaHangHoa item1 in ctcsghh)
                        {
                            if (item.MaHangHoa == item1.MaHangHoa && item.SoLuong >= item1.SoLuong)
                            {
                                item.PhanTramChietKhau = item1.PhanTramGiaBanBuon;
                                double dongiatruockhichietkhau = double.Parse(item.DonGia);
                                chietkhauthuongmai = 0;
                                if (hdbanbuon != null)
                                {
                                    if (hdbanbuon.PhanTramChietKhauThuongmai != 0)
                                    {
                                        chietkhauthuongmai = double.Parse(hdbanbuon.PhanTramChietKhauThuongmai.ToString());
                                    }
                                }
                                double dongiasaukhichietkhau = (dongiatruockhichietkhau - (dongiatruockhichietkhau * (double.Parse(item.PhanTramChietKhau) + chietkhauthuongmai)) / 100);
                                double thanhtiensaukhichietkhau = dongiasaukhichietkhau * item.SoLuong;
                                double thuesaukhichietkhau = (thanhtiensaukhichietkhau * double.Parse(item.ThueGTGT)) / 100;
                                item.ThanhTien = ((thanhtiensaukhichietkhau + thuesaukhichietkhau)).ToString();
                                array.Add(item);
                                kt = true;
                                break;
                            }
                        }
                        if (!kt)
                            array.Add(item);
                    }
                    hienthi = (Entities.ChiTietHDBanBuon[])array.ToArray(typeof(Entities.ChiTietHDBanBuon));
                    return hienthi;
                }
                else
                {
                    return chitiethdbanle;
                }
            }
            catch
            {
                return new Entities.ChiTietHDBanBuon[0];
            }
        }
        #endregion

        #region xử lý Khuyến mại tặng hàng
        Entities.ChiTietKhuyenMaiTangHang[] CheckKhuyenMaiTangHang()
        {
            try
            {
                ArrayList array = new ArrayList();
                foreach (Entities.KhuyenMaiTangHang item in khuyenmaitanghang)
                {
                    if (item.GiaTriTrangThai == "Đang sử dụng")
                    {
                        array.Add(item);
                    }
                }
                Entities.KhuyenMaiTangHang[] kmth = (Entities.KhuyenMaiTangHang[])array.ToArray(typeof(Entities.KhuyenMaiTangHang));

                array = new ArrayList();
                foreach (Entities.KhuyenMaiTangHang item in kmth)
                {
                    foreach (Entities.ChiTietKhuyenMaiTangHang item1 in chitietkhuyenmaitanghang)
                    {
                        if (item1.MaKhuyenMaiTangHang == item.MaKhuyenMaiTangHang)
                            array.Add(item1);
                    }
                }
                ctkmth = (Entities.ChiTietKhuyenMaiTangHang[])array.ToArray(typeof(Entities.ChiTietKhuyenMaiTangHang));
                return ctkmth;
            }
            catch
            {
                return new Entities.ChiTietKhuyenMaiTangHang[0];
            }
        }
        Entities.HangHoa[] manghanghoa;
        int tyle;
        Entities.ChiTietKhuyenMaiTangHang[] ctkmth;
        bool KhuyenMaiTangHang()
        {
            try
            {
                ctkmth = CheckKhuyenMaiTangHang();
                if (ctkmth.Length == 0)
                    return false;
                manghanghoa = CheckSuaHangHoaKhuyenMai();
                if (manghanghoa.Length != 0)
                    return true;
                return false;
            }
            catch
            {
                return false;
            }
        }

        Entities.HangHoa LayHangHoa(string mahangkhuyenmai, int soluog, bool kt)
        {
            try
            {
                List<Entities.HangHoa> hh = new List<Entities.HangHoa>();
                foreach (Entities.HangHoa item in hanghoa)
                {
                    hh.Add(item);
                }
                foreach (Entities.HangHoa item in Common.Utilities.CheckGoiHang(hanghoa, goihang, chitietgoihang))
                {
                    hh.Add(item);
                }
                foreach (Entities.HangHoa item in hh)
                {
                    if (item.MaHangHoa.ToUpper() == mahangkhuyenmai.ToUpper())
                    {
                        item.SoLuong = soluog;
                        item.KhuyenMai = kt;
                        return item;
                    }
                }
                return null;
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region Xử lý chuỗi mã hàng hóa
        bool XuLyChuoiMaHangHoa()
        {
            try
            {

                bool kt = false;
                mahanghoa = txtMaHangHoa.Text.ToUpper();

                if (khuyenmaitanghang == null)
                    khuyenmaitanghang = new KhuyenMaiTangHang.frmQuanLy().HienThi(date);
                if (chitietkhuyenmaitanghang == null)
                    chitietkhuyenmaitanghang = new KhuyenMaiTangHang.frmXuLy().HienThi();

                {
                    foreach (Entities.HangHoa item in hanghoa)
                    {
                        if (item.MaHangHoa.ToUpper() == mahanghoa.ToUpper())
                        {
                            txtMaHangHoa.Text = mahanghoa;
                            txtTenHangHoa.Text = item.TenHangHoa;
                            thuegtgt = LayThue(item.MaThue);
                            dongia = item.GiaBanBuon;
                            txtDonGia.Text = dongia;
                            kt = true;
                            break;
                        }
                    }
                    if (!kt)
                    {
                        if (goihang == null)
                            goihang = Common.StaticVariable.InterfaceObject.SelectGoiHang(new Entities.GoiHang("1"));
                        if (chitietgoihang == null)
                            chitietgoihang = Common.StaticVariable.InterfaceObject.SelectChiTietGoiHang(new Entities.ChiTietGoiHang("1"));
                        Entities.HangHoa[] hh1 = Common.Utilities.CheckGoiHang(hanghoa, goihang, chitietgoihang);

                        foreach (Entities.HangHoa item in hh1)
                        {
                            if (item.MaHangHoa.ToUpper() == mahanghoa.ToUpper())
                            {
                                txtMaHangHoa.Text = mahanghoa;
                                txtTenHangHoa.Text = item.TenHangHoa;
                                dongia = item.GiaBanBuon;
                                txtDonGia.Text = dongia;
                                kt = true;
                                checkgoihang = true;
                                break;
                            }
                        }
                        if (!kt)
                        {
                            MessageBox.Show(Common.MSG.MSG27(mahanghoa.ToUpper()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                            mahanghoa = "";
                            return false;
                        }
                    }
                }
                khuyenmai = false;

                return true;
            }
            catch
            {
                return false;
            }
        }

        void XuLy_Enter()
        {
            try
            {

                if (makho.Length == 0 || makho == "NULL")
                {
                    MessageBox.Show(Common.MSG.MSG28(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }
                if (txtMaKhachHang.Text.Length == 0 || txtMaKhachHang.Text == "<F4 - Tra cứu>")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaKhachHang.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }

                if (ValidateDetails())
                {

                    if (!XuLyChuoiMaHangHoa())
                    {
                        return;
                    }
                    if (!checkgoihang)
                    {
                        if (!KhuyenMaiTangHang())
                        {
                            if (txtMaHangHoa.Text.Length != 0 && txtMaHangHoa.Text != "<F4 - Tra cứu>")
                            {
                                NewRow();
                            }
                        }
                        else
                            AddRowMang();
                    }
                    else
                    {
                        if (!KhuyenMaiTangHang())
                        {
                            if (txtMaHangHoa.Text.Length != 0 && txtMaHangHoa.Text != "<F4 - Tra cứu>")
                            {
                                NewRow();
                            }
                        }
                        else
                            AddRowMang();

                    }
                }
            }
            catch
            {
            }
            finally
            {
                checkgoihang = false;
            }
        }
        int i = 0;
        void XuLyKeyUp()
        {
            int soluong = dgvHienThi.RowCount;

            if (soluong != 0)
            {
                if (i <= 0)
                    dgvHienThi.Rows[0].Selected = true;
                else if (i >= 0 && i < soluong)
                    dgvHienThi.Rows[i - 1].Selected = true;
            }
        }

        void XuLyKeyDown()
        {
            int soluong = dgvHienThi.RowCount;
            if (soluong != 0)
            {
                if (i < 0)
                    dgvHienThi.Rows[0].Selected = true;
                else if (i >= 0 && i < soluong - 1)
                    dgvHienThi.Rows[i + 1].Selected = true;
                else if (i == soluong - 1)
                    dgvHienThi.Rows[i].Selected = true;
            }
        }
        #endregion

        private void txtMaHangHoa_Click(object sender, EventArgs e)
        {
            txtMaHangHoa.SelectAll();
        }
        #endregion
    }
}
#endregion